package com.wenchao.libtts;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.widget.Toast;

import java.util.Locale;

/**
 * @author super
 */
public class TextToSpeechPlayer implements TextToSpeech.OnInitListener {

    private static TextToSpeechPlayer instance;

    public static TextToSpeechPlayer getInstance() {
        if (instance == null) {
            synchronized (TextToSpeechPlayer.class) {
                if (instance == null) {
                    instance = new TextToSpeechPlayer();
                }
            }
        }
        return instance;
    }

    private TextToSpeech tts;
    private Context context;

    private TextToSpeechPlayer() {
    }

    public void init(Context context) {
        this.context = context;
        tts = new TextToSpeech(context, this);
    }

    public void speak(String text) {
        if (tts != null && !TextUtils.isEmpty(text)) {
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    @Override
    public void onInit(int status) {
        // 判断是否转化成功
        if (status == TextToSpeech.SUCCESS) {
            //默认设定语言为中文，原生的android貌似不支持中文。
            int result = tts.setLanguage(Locale.CHINESE);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(context, "不可用！", Toast.LENGTH_SHORT).show();
                //不支持中文就将语言设置为英文
                tts.setLanguage(Locale.US);
            }
        }
    }

    public void destroyTTS(Context context) {
        if (tts != null && !tts.isSpeaking()) {
            tts.stop();
            tts.shutdown();
            tts = null;
        }
    }

}
